package org.tim.es.session;

import lombok.var;
import org.apache.logging.log4j.util.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.tim.es.ElasticsearchConstants;
import java.time.LocalDateTime;

public interface UserPrivareSessionResource extends ElasticsearchRepository<UserPrivateSession, String> {

    default Page<UserPrivateSession> findBy(String userId) {
        BoolQueryBuilder bQuery = new BoolQueryBuilder();
        if(Strings.isNotEmpty(userId)) {
            bQuery.should(new TermQueryBuilder("fromUserId", userId));
            bQuery.should(new TermQueryBuilder("toUserId", userId));
        }

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withQuery(bQuery);

        /* 根据最后的会话时间排序 */
        FieldSortBuilder startAtOrder_asc = SortBuilders.fieldSort("lastSessionAt");
        startAtOrder_asc.order(SortOrder.DESC);
        queryBuilder.withSort(startAtOrder_asc);

        return this.search(queryBuilder.build());
    }

    default Page<UserPrivateSession> findBy(String userId, LocalDateTime dateTime) {
        BoolQueryBuilder bQuery = new BoolQueryBuilder();
        if(Strings.isNotEmpty(userId)) {
            bQuery.should(new TermQueryBuilder("fromUserId", userId));
            bQuery.should(new TermQueryBuilder("toUserId", userId));
        }

        if(dateTime != null) {
            var startAt = ElasticsearchConstants.DATE_HOUR_MINUTE_SECOND.format(dateTime);
            bQuery.must().add(new RangeQueryBuilder("lastSessionAt").gte(startAt));
        }

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withQuery(bQuery);

        /* 根据最后的会话时间排序 */
        FieldSortBuilder startAtOrder_asc = SortBuilders.fieldSort("lastSessionAt");
        startAtOrder_asc.order(SortOrder.DESC);
        queryBuilder.withSort(startAtOrder_asc);

        return this.search(queryBuilder.build());
    }
}
